<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link href="css/base.css" rel="stylesheet">
    <link href="css/head.css" rel="stylesheet">

    <link href="css/change_pet.css" rel="stylesheet">
</head>
<body>
    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/head.js"></script>
    <script src="js/upload.js"></script>
    <script src="js/Utils.js"></script>

    <script src="js/mock.js"></script>
    <script src="js/mock/change_pet.js"></script>

    <div class="head"></div>

    <div class="main">
        <div class="uploadBox"></div>

        <div class="form">
            <div>
                <span>名称</span>
                <input type="text" id="name">
            </div>
            <div>
                <span>类型</span>
                <select id="type"></select>
            </div>
            <div>
                <span>品种</span>
                <select id="kind"></select>
            </div>
            <div>
                <span>库存</span>
                <input type="text" id="stock">
            </div>
            <div>
                <span>价格</span>
                <input type="text" id="price">
            </div>

            <div>
                <span>简介</span>
                <textarea id="intro" style="width:87%;height:200px;resize: none;"></textarea>
            </div>

            <div>
                上架<input type="radio"  name="added" value="1">

                下架<input type="radio"  name="added" value="0">
            </div>
        </div>

        <div class="change">
            <div class="button" style="width: 100%;" id="change">修改</div>
        </div>


        <div class="commentBox">

        </div>

    </div>

    <script>
        let paramter = getURIParameter()
        let commentList = null
        let id = paramter.id

        function checkParameter(){
            let name = $("#name").val()

            let stock = $("#stock").val()
            let price = $("#price").val()
            let intro = $("#intro").val()

            let obj = {
                name, stock, price, intro
            }


            for(let k in obj){
                if(obj[k] == ""){
                    alert("请填写完整数据")
                    return false
                }
            }

            if(Number.isNaN(Number(price))){
                alert("价格必须为数字")
                return false
            }

            else if(Number.isNaN(Number(stock))){
                alert("库存必须为数字")
                return false
            }

            return true
        }

        function getAddedStatus(){
            let added = $('input:radio[name=added]').eq(0)[0]['checked']

            if(added) return "1"

            else return "0"
        }

        function changeInfoEvent(){
            $('#change').click(function(){
                let name = $("#name").val()

                let stock = $("#stock").val()
                let price = $("#price").val()
                let intro = $("#intro").val()
                
                let added = getAddedStatus()

                let type_selected_index = $("#type")[0].selectedIndex
                let kind_selected_index = $("#kind")[0].selectedIndex

                let type_id = $("#type")[0].options[type_selected_index].value
                let kind_id = $("#kind")[0].options[kind_selected_index].value

                if(!checkParameter())
                    return

                data = {
                    name, type_id, kind_id, stock, price, added, intro, id
                }

                data = JSON.stringify(data)
                $.ajax({
                    data,
                    url: baseUrl + 'change_pet.php',
                    type: 'POST',
                    success: function(res){
                        if(typeof(res) == 'string')
                            res = JSON.parse(res)

                        if(res.code == 200){
                            alert(res.msg)
                        }

                        else    alert(res.msg)
                    }
                })
            })
        }

        function changeUploadEvent(){
            $('#upload').change(function(event){
                let file = event.target.files[0]

                let formData = new FormData

                let imgUrl = null

                formData.append('file', file)

                let upload = $.ajax({
                    data : formData,
                    contentType: false,
                    processData: false,
                    url: baseUrl + 'upload.php',
                    type: 'POST',
                    success: function(res){
                    }
                })

                let changeImg = function(imgUrl){
                    data = {
                        id,
                        imgUrl
                    }

                    data = JSON.stringify(data)
                    return $.ajax({
                        data,
                        url: baseUrl + 'change_pet_avatar.php',
                        type: 'POST',
                        success : function(res){
                            
                        }
                    })
                }

                upload.then(res => {
                    if(typeof(res) == 'string')
                        res = JSON.parse(res)
                    
                    if(res.code == 200){
                        imgUrl = res.data.imgUrl

                        return changeImg(imgUrl)
                    }
                        
                    else    alert(res.msg)
                }).then(res => {
                    if(!res)
                        return

                    if(typeof(res) == 'string')
                        res = JSON.parse(res)

                    if(res.code == 200){
                        alert(res.msg)
                        $(".avatar img").attr("src", baseUrl + imgUrl)
                    }
                    else alert(res.msg)
                })
            })
        }

        function delComment(id){
            let data = {
                id
            }


            $.ajax({
                data,
                url: 'http://localhost/del_comment.php',
                type: 'POST',
                success: function(res){
                    if(typeof(res) == 'string')
                        res = JSON.parse(res)
                    
                    if(res.code == 200){
                        alert(res.msg)
                        removeComment(id)
                        renderComment()
                    }

                    else    alert(res.msg)
                }
            })
        }

        function renderComment(){
                if(!commentList)
                    return

                $('.main .commentBox').empty()

                for(let i = 0; i < commentList.length; i++){
                    $('.main .commentBox').append(`
                        <div class="comment">
                            <div class="avatar">
                                <img src="${commentList[i].avatar}" />
                            </div>    

                            <div class="content">
                                <div class="info">
                                    <div class="name">${commentList[i].username}</div>
                                    <div class="date">${commentList[i].date}</div>
                                </div>
                                <div>
                                    ${commentList[i].comment}    
                                </div>
                            </div>

                            <div class="operation">
                                <div class="button" onclick="delComment('${commentList[i].id}')">删除</div>
                            </div>
                        </div>
                    `)
                }
            }

        function removeComment(id){
                for(let i = 0; i < commentList.length; i++){
                    if(commentList[i].id == id){
                        
                        commentList.splice(i,1)
                        break
                    }
                }
            }

        $('document').ready(function(){

            if(!id)
                location.href = "pet_manage.html"


            changeInfoEvent()
            changeUploadEvent()

            //获取所有宠物的类别
            $.ajax({
                url : baseUrl + 'pet_types.php',
                type: 'GET',
                success: function(res){
                    if(typeof(res) == 'string')
                        res = JSON.parse(res)

                    if(res.code == 200){
                        renderType(res.data)
                    }else alert(res.msg)
                }
            })

            //获取所有宠物的品种
            $.ajax({
                url : baseUrl + 'get_kinds.php',
                type: 'GET',
                success: function(res){
                    if(typeof(res) == 'string')
                        res = JSON.parse(res)

                    if(res.code == 200){
                        renderKind(res.data)
                    }else alert(res.msg)
                }
            })

            //获取该宠物的数据
            $.ajax({
                url: baseUrl + 'get_pet.php?id='+id,
                type: 'GET',
                success: function(res){
                    if(typeof(res) == 'string')
                        res = JSON.parse(res)

                    if(res.code == 200){
                        render(res.data)
                    }else
                        alert(res.msg)
                }
            })

            function render(data){
                commentList = data.commentList

                $('.main .uploadBox').append(`
                    <div class="avatar">
                        <img src="${baseUrl + data.image}" />
                    </div>
                `)

                $("#name").val(data.name)

                $("#stock").val(data.stock)
                $("#price").val(data.price)
                $("#intro").val(data.intro)

                let type_id = data['type_id']
                let kind_id = data['kind_id']

                let type_option = $("#type option")
                let kind_option = $("#kind option")

                for(let i = 0; i < type_option.length; i++){
                    let the_option = type_option.eq(i)

                    if(the_option.val() == type_id)
                        type_option.eq(i).attr("selected", true)
                }

                for(let i = 0; i < kind_option.length; i++){
                    let the_option = kind_option.eq(i)

                    if(the_option.val() == kind_id)
                        the_option.attr("selected", true)
                }

                $("#type").append()

                if(Number.parseInt(data.added))
                    $('input:radio[name=added]').eq(0).attr('checked', true)
                else
                    $('input:radio[name=added]').eq(1).attr('checked', true)

                
                renderComment()
            }

            function renderType(data){
                if(data){
                    for(let d of data){
                        $('#type').append(`
                            <option value="${d.id}">${d.type}</option>
                        `)
                    }
                }
            }

            function renderKind(data){
                if(data){
                    for(let d of data){
                        $('#kind').append(`
                            <option value="${d.id}">${d.kind}</option>
                        `)
                    }
                }
            }


        })
    </script>
    
</body>
</html>